<template>
  <div class="container">
    <div class="filter-container">
      <div class="filter-item">
        <el-input v-model="q.code" placeholder="位号" style="width: 120px" />
      </div>
      <div class="filter-item">
        <el-input v-model="q.itemCode" placeholder="指标编码" style="width: 120px" />
      </div>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button class="filter-item" type="default" @click="handleSearch">刷新</el-button>
      <div class="tool-control pull-right">
        <el-button
          class="filter-item"
          style="margin-right: 10px;"
          type="primary"
          @click="fileDownload"
        >文件下载
        </el-button>
        <el-upload action :show-file-list="false" :http-request="importPhysicalPort" class="filter-item">
          <el-button
            :loading="importLoading"
            type="primary"
            icon="el-icon-upload2"
          >导入配置
          </el-button>
        </el-upload>
        <el-button
          :loading="downloadLoading"
          class="filter-item"
          type="primary"
          icon="el-icon-download"
          @click="exportPhysicalPort"
        >导出配置
        </el-button>
        <el-button
          :loading="isSubmitLoading"
          :disabled="statistics.configApplyStatus!==1"
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-open"
          @click="useConfigSetting()"
        >应用配置
        </el-button>
        <el-button
          :loading="isSubmitLoading"
          :disabled="statistics.managerConnectionStatus!==1 || statistics.configSyncStatus!==1"
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-refresh"
          @click="syncConfigSetting()"
        >上传配置
        </el-button>
      </div>
    </div>
    <el-table :key="tableKey" v-loading="tableLoading" :data="dataElements" border fit highlight-current-row :row-class-name="tableRowClassName" style="width: 100%;">
<!--      <el-table-column label="ID" prop="id" align="center" width="60"></el-table-column>-->
      <!--      <el-table-column label="通道ID" prop="portId" align="center" width="90"></el-table-column>-->
      <el-table-column label="位号" prop="code" min-width="90"></el-table-column>
      <el-table-column label="指标编码" prop="itemCode" align="center" min-width="100"></el-table-column>
      <el-table-column label="描述" prop="description" min-width="190"></el-table-column>
      <el-table-column label="数据点类型" align="center" min-width="120px">
        <template slot-scope="{row}">
          {{ transType(row.type) }}
        </template>
      </el-table-column>
      <el-table-column label="数值" prop="value" align="center" min-width="90"></el-table-column>
      <el-table-column label="单位" prop="unit" align="center" min-width="90"></el-table-column>
      <el-table-column label="时间戳" align="center" min-width="160">
        <template slot-scope="scope">
          <span>{{ scope.row.collectTime ? transDate(scope.row.collectTime) : ''}}</span>
        </template>
      </el-table-column>
      <el-table-column label="质量戳" align="center" min-width="90">
        <template slot-scope="{row}">
          {{ row.quality }}
        </template>
      </el-table-column>
      <el-table-column label="量程上限" prop="rangeLH" align="center" min-width="90"></el-table-column>
      <el-table-column label="量程下限" prop="rangeLL" align="center" min-width="90"></el-table-column>
      <el-table-column label="高高报阈值" prop="majorHighAlarmThreshold" align="center" min-width="120"></el-table-column>
      <el-table-column label="高报阈值" prop="highAlarmThreshold" align="center" min-width="120"></el-table-column>
      <el-table-column label="低报阈值" prop="lowAlarmThreshold" align="center" min-width="120"></el-table-column>
      <el-table-column label="低低报阈值" prop="majorLowAlarmThreshold" align="center" min-width="120"></el-table-column>
    </el-table>
    <pagination v-show="totalCount > 0" :total="totalCount" :page-index.sync="q.page" :page-size.sync="q.size" @pagination="getValuePageDataElement" />
  </div>
</template>

<script>
import { exportPhysicalPort, importPhysicalPort } from "@/api/physicalPort";
import { getStatistics, applyConfigToNorth, applyConfigToSouth } from "@/api/gateway";
import { getValuePageDataElement } from "@/api/dataElement";
import { dataEleTypeOptions } from "@/utils/enums.js";
import Pagination from "@/components/Pagination";
import moment from "moment";

export default {
  components: {
    pagination: Pagination
  },
  props: {
    equipment: {
      type: Object,
      'default': {}
    }
  },
  data() {
    return {
      dataEleTypeOptions,
      statistics: {},
      isSubmitLoading: false,
      importLoading: false,
      downloadLoading: false,
      tableLoading: false,
      tableKey: 0,
      dataElements: [],
      q: {
        portId: undefined,
        equipId: undefined,
        itemCode: undefined,
        code: undefined,
        page: 1,
        size: 10,
        type: undefined
      },
      totalCount: 0
    };
  },
  computed: {},
  watch: {
    "equipment.id": function(newVal) {
      this.q.portId = this.equipment.portId;
      this.q.equipId = newVal;
      this.q.page = 1;
      this.getValuePageDataElement();
    }
  },
  created() {
    this.getValuePageDataElement();
  },
  methods: {
    handleSearch() {
      this.getValuePageDataElement();
    },
    getStatistics() {
      this.isSubmitLoading = true;
      getStatistics().then(result => {
        this.statistics = result;
        this.isSubmitLoading = false;
      });
    },
    getValuePageDataElement() {
      this.tableLoading = true;
      getValuePageDataElement(this.q).then(result => {
        this.dataElements = result.content;
        this.totalCount = result.totalElements;
        this.tableLoading = false;
      });
      this.getStatistics();
    },
    transType(type) {
      let returnVal = "";
      switch (type) {
        case 1:
          returnVal = "模拟量";
          break;
        case 2:
          returnVal = "开关量";
          break;
        case 3:
          returnVal = "其他";
          break;
      }
      return returnVal;
    },
    transDate(timestamp) {
      return moment(timestamp * 1000).format("YYYY-MM-DD HH:mm:ss");
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.quality && row.quality > 0) {
        return "danger-row";
      }
      return "";
    },
    useConfigSetting() {
      this.$confirm("该操作将应用配置， 是否继续?", "确定执行应用配置操作吗？", { type: "warning" })
        .then(() => {
          const loading = this.$loading({
              lock: true,
              text: '请稍候...',
              spinner: 'el-icon-loading',
              background: 'rgba(255, 255, 255, 0.7)'
            });
          applyConfigToSouth()
            .then(() => {
              this.$message({
                message: "应用配置成功",
                type: "success"
              });
              loading.close();
              this.getStatistics();
            })
            .catch(() => {
              loading.close();
            });
        })
        .catch(() => {

        });
    },
    syncConfigSetting() {
      this.$confirm("该操作将上传配置， 是否继续?", "确定上传配置吗？", { type: "warning" })
        .then(() => {
          const loading = this.$loading({
              lock: true,
              text: '请稍候...',
              spinner: 'el-icon-loading',
              background: 'rgba(255, 255, 255, 0.7)'
            });
          applyConfigToNorth()
            .then(() => {
              this.$message({
                message: "上传配置成功",
                type: "success"
              });
              loading.close();
              this.getStatistics();
            })
            .catch(() => {
              loading.close();
            });
        })
        .catch(() => {

        });
    },
    importPhysicalPort(fileObj) {
      this.$confirm("批量导入将清空并覆盖已配置数据，确定继续吗？", "确定执行导入操作吗？", {
        type: "warning"
      })
        .then(() => {
          const loading = this.$loading({
              lock: true,
              text: '请稍候...',
              spinner: 'el-icon-loading',
              background: 'rgba(255, 255, 255, 0.7)'
            });
          const param = new FormData();
          param.append("file", fileObj.file);
          importPhysicalPort(param).then(result => {
            loading.close();
            this.getFullPageDataElement();
            this.$message({
              message: "导入成功",
              type: "success"
            });
          });
        })
        .catch(() => {
        });
    },
    exportPhysicalPort() {
      const loading = this.$loading({
              lock: true,
              text: '请稍候...',
              spinner: 'el-icon-loading',
              background: 'rgba(255, 255, 255, 0.7)'
            });
      exportPhysicalPort().then(result => {
        this.download(result, '配置.xlsx');
        loading.close();
      });
    },
    download(data, name) {
      const blob = new Blob([data]);
      const fileName = name;
      if ('download' in document.createElement('a')) { // 非IE下载
        const elink = document.createElement('a');
        elink.download = fileName;
        elink.style.display = 'none';
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href); // 释放URL 对象
        document.body.removeChild(elink);
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName);
      }
    },
    fileDownload() {
      this.$router.push({
        name: 'fileDownload'
      })
    }
  }
};
</script>

<style lang="scss">
.full-container {
  min-height: calc(100vh - 50px);
}
div.filter-item{
  display: inline-block;
  margin-right: 10px;
}
.el-table .danger-row {
  color: #f56c6c !important;
}
</style>
